package com.freework.util.excel.read.service.rowToObject;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;

import com.freework.util.NumberUtil;
import com.freework.util.excel.read.vo.ColVO;

public class RowToObjectImpi implements RowToObjectI {
	SetValueI[] setValue=null;
	Class clazz=null;
	public Object createObject() {
		try {
			return clazz.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	private  Map<String,Method> getMapReadMethod(Class clazz){
		Map<String,Method> map=new HashMap<String,Method>();
		PropertyDescriptor	ps[]=PropertyUtils.getPropertyDescriptors(clazz);
		for (PropertyDescriptor propertyDescriptor : ps) {
			
			map.put(propertyDescriptor.getName(), propertyDescriptor.getWriteMethod());
		}
		return map;
	}
	public SetValueI[] getSetValues() {
		
		return setValue;
	}
	
	public void initSetValues( Map<String,Method> map,List<ColVO> list){
		setValue =new SetValueI[list.size()];
		int i=0;
		for (ColVO colVO : list) {
			setValue[i]=createSetValue(map,colVO);
			i++;
		}
	}
	
	private SetValue createSetValue( Map<String,Method> map,ColVO colVO){
		Method method=map.get(colVO.getColname());
		SetValue SetValue=new SetValue();
		SetValue.classtype=method.getParameterTypes()[0];
		SetValue.method=method;
		return SetValue;
	}
	
	public void init(List<ColVO> list,Class clazz) {
		this.clazz=clazz;
		 Map<String,Method> map=getMapReadMethod(clazz);
		 initSetValues(map, list);
		 
	}
	class SetValue extends AbstractSetValue{
		Method method=null;
		Class classtype=null;
		public void setObjValue(Object obj, Object value, ColVO vo) {
			try {
				method.invoke(obj,value);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		
			
		}

		@Override
		Class getClass(ColVO vo) {
			// TODO Auto-generated method stub
			return classtype;
		}

		
	}

}
